package com.hightrast.service.service.impl;

import cn.hutool.core.util.StrUtil;
import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.baomidou.mybatisplus.core.conditions.update.LambdaUpdateWrapper;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.hightrast.service.api.baseEntity.exception.ServiceException;
import com.hightrast.service.api.domain.qo.rastVendor.AddUserVendorQo;
import com.hightrast.service.api.entity.RastUserVendor;
import com.hightrast.service.api.entity.RastVendor;
import com.hightrast.service.mapper.RastUserVendorMapper;
import com.hightrast.service.service.IRastUserVendorService;
import com.hightrast.service.service.IRastVendorService;
import com.hightrast.service.util.BaseEntityUtil;
import lombok.extern.slf4j.Slf4j;
import org.springframework.context.annotation.Lazy;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

import javax.annotation.Resource;
import java.util.List;
import java.util.Objects;

/**
 * <p>
 * 用户品牌关联表 服务实现类
 * </p>
 *
 * @author hx
 * @since 2025-01-11
 */
@Service
@Slf4j
public class RastUserVendorServiceImpl extends ServiceImpl<RastUserVendorMapper, RastUserVendor> implements IRastUserVendorService {

    @Lazy
    @Resource
    private IRastVendorService vendorService;

    /**
     * 获取这些品牌关联的用户
     * @param vendors
     * @return
     */
    @Override
    public List<RastUserVendor> queryUserVendors(List<String> vendors) {

        return this.baseMapper.selectUserVendors(vendors);

    }


    /**
     * 用户绑定、修改品牌，每次先删再增 管理者权限操作
     *
     * @param qo
     */
    @Transactional
    @Override
    public void saveUpdateVendorUser(AddUserVendorQo qo) {
        RastUserVendor rastUserVendor = this.getOne(new LambdaQueryWrapper<RastUserVendor>().eq(RastUserVendor::getVendorId, qo.getVendorId()));
        if(Objects.nonNull(rastUserVendor)){
            if(!Objects.equals(rastUserVendor.getUserId(),qo.getUserId())){
                // 当前品牌已绑定其他用户
               throw new ServiceException("The current brand has already been linked to other users");
            }
        }else {
            this.remove(new LambdaQueryWrapper<RastUserVendor>().eq(RastUserVendor::getUserId, qo.getUserId()));
            RastUserVendor userVendor = new RastUserVendor();
            userVendor.setUserId(qo.getUserId());
            userVendor.setVendorId(qo.getVendorId());
            userVendor.setVendor(qo.getVendor());
            BaseEntityUtil.save(userVendor);
            this.save(userVendor);
        }
        if(Objects.nonNull(qo.getVendorId()) && StrUtil.isNotEmpty(qo.getRemark())){
            vendorService.update(new LambdaUpdateWrapper<RastVendor>().set(RastVendor::getRemark,qo.getRemark()).eq(RastVendor::getId,qo.getVendorId()));
        }
    }
}
